from django.core.paginator import Paginator
from public.function import Public
from django.shortcuts import  get_object_or_404
from django.http import JsonResponse
from pymongo import MongoClient
import pymysql

class JuncheePaginator(Paginator):
    def __init__(self, object_list, per_page, range_num=5, orphans=0, allow_empty_first_page=True):
        Paginator.__init__(self, object_list, per_page, orphans, allow_empty_first_page)
        self.range_num = range_num

    def page(self, number):
        self.page_num = number
        return super(JuncheePaginator, self).page(number)

    def _page_range_ext(self):
        num_count = 2 * self.range_num + 1
        if self.num_pages <= num_count:
            return range(1, self.num_pages + 1)
        num_list = []
        num_list.append(self.page_num)
        for i in range(1, self.range_num + 1):
            if self.page_num - i <= 0:
                num_list.append(num_count + self.page_num - i)
            else:
                num_list.append(self.page_num - i)

            if self.page_num + i <= self.num_pages:
                num_list.append(self.page_num + i)
            else:
                num_list.append(self.page_num + i - num_count)
        num_list.sort()
        return num_list

    page_range_ext = property(_page_range_ext)




class Mysql_Public(Public):

    def check_repl_status(self):
        sid = self.request.POST.get('serverid')
        server = get_object_or_404(self.models, pk=sid)
        config={'host':str(server.server),
                'port':server.port, "user":server.db_user,'cursorclass':pymysql.cursors.DictCursor,
                                   "passwd":server.db_password, "charset":"utf8",}
        try:
            conn = pymysql.connect(**config)
            cursor=conn.cursor()
            if server.mysql_type == "standby":
                querystring=""
            elif server.mysql_type == "master":
                querystring="show master status"
            cursor.execute(querystring)
            data=cursor.fetchall()
            return JsonResponse({"msg": str(data)})
            conn.close()
        except Exception as e:
            print(e)
            return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">%s</p>''' % str(e)})

    def check_status(self):
        sid = self.request.POST.get('serverid')
        server = get_object_or_404(self.models, pk=sid)

        try:
            conn = pymysql.connect(host=str(server.server), port=server.port, user=server.db_user,
                                   passwd=server.db_password, charset="utf8")
        except Exception as e:
            print(e)
            return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">%s</p>''' % str(e)})
        return JsonResponse({"msg": "数据库链接正常"})


    def update_mysql_passwd(self):
        sid = self.request.POST.get('serverid')
        server = get_object_or_404(self.models, pk=sid)
        minion_id=str(server.server)
        port=server.port
        user=server.db_user
        func="cmd.run"
        if server.mysql_type == "standby":
            args = "cat /data/save/mysql_%s_%s" % (server.port,user)
        else:
            args="cat /data/save/mysql_%s" %(user)
        try:
            db_pwd=self.saltfunction(minion_id,func,args)
            server.db_password=db_pwd
            server.save()
            return JsonResponse({"msg": "更新数据库密码成功"})
        except Exception as e:
            return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">%s</p>''' % str(e)})


    def saltfunction(self,minionid,func,args):
        print(args)
        saltreturn = self.Saltapi.remote_execution(minionid, fun=func, arg=args)
        return saltreturn



class Mongo_Public(Mysql_Public):
    def update_mongo_passwd(self):
        sid = self.request.POST.get('serverid')
        server = get_object_or_404(self.models, pk=sid)
        minion_id=str(server.server)
        port=server.port
        user=server.db_user
        stype=server.mongo_type
        func="cmd.run"
        user ='admin'

        args="cat /data/save/mongo_%s_%s_%s_passwd" %(stype,port,user)
        try:
            db_pwd=self.saltfunction(minion_id,func,args)

            server.db_password=db_pwd
            server.save()
            return JsonResponse({"msg": "更新数据库密码成功"})
        except Exception as e:
            return JsonResponse({"msg": '''<p style="color:red;font-size:9px ">%s</p>''' % str(e)})

    def check_status(self):
        sid = self.request.POST.get('serverid')
        server = get_object_or_404(self.models, pk=sid)
        if server.db_user:
            uri = 'mongodb://%s:%s@%s:%s/%s' % (server.db_user, server.db_password, str(server.server), server.port, "admin")
        else:
            uri = 'mongodb://%s:%s/%s' % (str(server.server), server.port, "admin")

        try:
            client = MongoClient(uri)
            db = client['admin']
            db.collection_names()
        except Exception as e:
            print(e)
            return JsonResponse({"msg": '''<p style="color:red;font-size:9px ">%s</p>''' % str(e)})
        return JsonResponse({"msg": "数据库链接正常"})
